<template>
  <div class="login-container">
    <div class="login-box">
      <div class="logo">
        <img src="@/assets/logo.svg" alt="Logo" />
        <h1>苍穹外卖管理系统</h1>
      </div>
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.rememberMe">
            记住密码（2天）
          </el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { employeeApi } from '@/api'
import { useAppStore } from '@/stores/app'
import axios from 'axios'

const router = useRouter()
const appStore = useAppStore()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: '',
  rememberMe: false
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 缓存键名
const CACHE_KEY = 'sky_takeaway_login_cache'
const CACHE_EXPIRY_DAYS = 2

// 保存登录信息到缓存
const saveLoginCache = (username, password) => {
  const cacheData = {
    username,
    password,
    timestamp: Date.now()
  }
  localStorage.setItem(CACHE_KEY, JSON.stringify(cacheData))
}

// 从缓存加载登录信息
const loadLoginCache = () => {
  try {
    const cached = localStorage.getItem(CACHE_KEY)
    if (!cached) return false

    const cacheData = JSON.parse(cached)
    const now = Date.now()
    const expiry = CACHE_EXPIRY_DAYS * 24 * 60 * 60 * 1000 // 2天的毫秒数

    // 检查是否过期
    if (now - cacheData.timestamp > expiry) {
      localStorage.removeItem(CACHE_KEY)
      return false
    }

    // 自动填充登录表单
    loginForm.username = cacheData.username
    loginForm.password = cacheData.password
    loginForm.rememberMe = true
    return true
  } catch (error) {
    console.error('加载登录缓存失败:', error)
    localStorage.removeItem(CACHE_KEY)
    return false
  }
}

// 清除登录缓存
const clearLoginCache = () => {
  localStorage.removeItem(CACHE_KEY)
}

const handleLogin = async () => {
  if (!loginForm.username || !loginForm.password) {
    // 关闭所有现有的消息提示
    ElMessage.closeAll()
    // 使用 ElMessage 显示错误
    ElMessage.error('请输入用户名和密码')
    return false
  }
  
  loading.value = true
  
  try {
    console.log('尝试登录请求:', loginForm)
    
    // 直接使用原始的axios
    const res = await axios.post('/api/admin/employee/login', loginForm)
    
    console.log('登录响应原始数据:', res)
    
    if (res.data && res.data.code === 1) {
      console.log('登录成功, 响应数据:', res.data)
      
      // 将token存储到localStorage中
      localStorage.setItem('token', res.data.data.token)
      
      // 提取用户ID 
      const userId = res.data.data.id
      
      if (!userId) {
        console.error('登录响应中未找到用户ID')
        ElMessage.warning('登录成功但无法获取用户信息')
      }
      
      console.log('成功获取到用户ID:', userId)
      // 将用户ID单独保存，方便调试
      localStorage.setItem('userId', userId)
      
      try {
        // 立即获取用户完整信息
        console.log('尝试获取完整用户信息')
        const employeeRes = await axios.get(`/api/admin/employee/${userId}`, {
          headers: { token: res.data.data.token }
        })
        
        console.log('获取员工信息响应:', employeeRes.data)
        
        if (employeeRes.data && employeeRes.data.code === 1) {
          const userData = employeeRes.data.data
          console.log('获取到完整用户数据:', userData)
          
          // 将完整用户信息存储到Pinia store
          const userInfo = {
            id: userId,
            username: userData.username,
            name: userData.name,
            status: userData.status,
            phone: userData.phone,
            idNumber: userData.idNumber,
            sex: userData.sex
          }
          
          appStore.setUserInfo(userInfo)
          
          // 检查是否正确存储了用户信息
          console.log('存储到Pinia的用户信息:', appStore.userInfo)
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
        } else {
          // 存储基本信息
          const userInfo = {
            id: userId,
            username: loginForm.username,
            name: res.data.data.name || loginForm.username
          }
          
          appStore.setUserInfo(userInfo)
          
          console.log('保存基本用户信息:', userInfo)
          localStorage.setItem('userInfo', JSON.stringify(userInfo))
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 存储基本信息
        const userInfo = {
          id: userId,
          username: loginForm.username,
          name: res.data.data.name || (loginForm.username === 'admin' ? '管理员' : loginForm.username)
        }
        appStore.setUserInfo(userInfo)
        localStorage.setItem('userInfo', JSON.stringify(userInfo))
      }
      
      // 关闭所有现有的消息提示
      ElMessage.closeAll()
      ElMessage.success('登录成功')
      
      // 登录成功后保存缓存（如果用户选择了记住密码）
      if (loginForm.rememberMe) {
        saveLoginCache(loginForm.username, loginForm.password)
      } else {
        clearLoginCache()
      }
      
      // 跳转至首页
      setTimeout(() => {
        router.push('/')
      }, 100)
    } else {
      // 登录失败，关闭所有现有的消息提示
      ElMessage.closeAll()
      console.log('登录失败:', res.data.msg)
      // 添加一个小延迟，确保消息在当前页面显示
      setTimeout(() => {
        ElMessage.error(res.data.msg || '用户名或密码错误')
      }, 50)
      // 清空密码
      loginForm.password = ''
      // 确保不跳转，停留在登录页面
      loading.value = false
      return false
    }
  } catch (error) {
    console.error('登录请求错误:', error)
    
    // 根据不同的错误类型设置错误消息
    let errorMsg = '登录失败，请稍后重试'
    if (error.response) {
      if (error.response.data && error.response.data.msg) {
        errorMsg = error.response.data.msg
      } else if (error.response.status === 401) {
        errorMsg = '用户名或密码错误'
      }
    } else {
      errorMsg = '网络连接失败，请检查网络'
    }
    
    // 关闭所有现有的消息提示
    ElMessage.closeAll()
    // 使用 ElMessage 显示错误，添加一个小延迟
    setTimeout(() => {
      ElMessage.error(errorMsg)
    }, 50)
    // 清空密码
    loginForm.password = ''
    // 确保不跳转，停留在登录页面
    loading.value = false
    return false
  } finally {
    loading.value = false
  }
}

// 组件挂载时加载缓存
onMounted(() => {
  loadLoginCache()
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 1001;
}

.logo {
  text-align: center;
  margin-bottom: 30px;
}

.logo img {
  width: 80px;
  height: 80px;
}

.logo h1 {
  margin-top: 15px;
  font-size: 22px;
  color: #333;
}

.login-form {
  margin-top: 30px;
}

.login-button {
  width: 100%;
}

/* 自定义 ElMessage 样式，提高 z-index */
:global(.el-message) {
  min-width: 300px;
  padding: 15px 20px;
  border-radius: 8px;
  font-size: 14px;
  z-index: 10000 !important;
}

:global(.el-message--success) {
  background-color: #f0f9ff;
  border: 1px solid #67c23a;
  color: #67c23a;
}

:global(.el-message--success .el-message__content) {
  color: #67c23a;
  font-weight: 500;
}

:global(.el-message--error) {
  background-color: #fef0f0;
  border: 1px solid #f56c6c;
  color: #f56c6c;
}

:global(.el-message--error .el-message__content) {
  color: #f56c6c;
  font-weight: 500;
}
</style> 